#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tkinter as tk
from typing import Tuple

from AbstractGrid import AbstractGrid
from a2_solution import Inventory, Position
from constants import *


class InventoryView(AbstractGrid):
    def __init__(self, master: tk.Tk, rows: int, **kwargs):
        """
        The parameter rows should be set to the number of rows in the game map
        Args:
            master:
            rows:
            **kwargs:
        """
        self.rows = rows
        self.master = master
        self.kwargs = kwargs
        AbstractGrid.__init__(self, master, rows, 2, INVENTORY_WIDTH, rows * CELL_SIZE, bg=LIGHT_PURPLE, **kwargs)

    def _draw_inventory_title(self):
        """
        draw inventory view's title
        Returns:

        """
        p0 = Position(0, 0)
        p1 = Position(1, 0)
        x0, y = self.get_position_center(p0)
        x1, _ = self.get_position_center(p1)
        x = int((x0 + x1) / 2)
        self.create_text(x, y, text=INVENTORY_TITLE, font=FONT_TEXT)

    def draw(self, inventory: Inventory):
        """
        Draws the inventory label and current items with their remaining lifetimes.
        Args:
            inventory:

        Returns:
        """
        self.delete('all')
        self._draw_inventory_title()

        font_color = BLACK
        for i, pickup in enumerate(inventory.get_items()):
            position_name = Position(0, 1 + i)
            position_time = Position(1, 1 + i)
            name = pickup.__class__.__name__
            time = pickup.get_lifetime()
            if pickup.is_active():
                font_color = WHITE
                x_min, y_min, _, _ = self.get_bbox(position_name)
                _, _, x_max, y_max = self.get_bbox(position_time)
                self.create_rectangle(x_min, y_min, x_max, y_max, fill=DARK_PURPLE)
            name_xy = self.get_position_center(position_name)
            time_xy = self.get_position_center(position_time)
            self.create_text(name_xy, text=name, fill=font_color)
            self.create_text(time_xy, text=time, fill=font_color)

    def toggle_item_activation(self, pixel: Tuple[int, int], inventory: Inventory):
        """
        Activates or deactivates the item(if one exists) in the row containing the pixel.
        Args:
            pixel:
            inventory:
        Returns:
        """
        position = self.pixel_to_position(pixel)
        index = position.get_y() - 1
        items = inventory.get_items()
        if index >= len(items):
            return  # do nothing
        item_click = items[index]
        item_click.toggle_active()
        for i, item in enumerate(items):
            if i != index and item.is_active():
                item.toggle_active()
        self.draw(inventory)  # show color change immediately
